from app.utils.clickhouse import ClickHouseUtil

# from app.utils.logger import Logger
import numpy as np
from app.utils.logger_helper import logger


# 获取数据
def fetch_data(kkbh, start_date, end_date, hour):
    sql = '''
        select 
            concat(toString(`day`), ' ', `hour`) as time, `real_count` as count
        from
            t_car_flow_history
        where `kkbh` = '{}' 
        and `day` between toDate('{}') and toDate('{}')
        and `hour` = '{}'
    '''.format(kkbh, start_date, end_date, hour)

    # Logger.all_log().logger.debug('执行的sql:' + sql)
    logger.info('执行的sql:' + sql)
    # print('执行的sql:' + sql)
    return ClickHouseUtil().exec_pd(sql)


# 持久化数据
def save_data(data):
    sql = 'insert into t_car_flow_predict(kkbh, day, hour, predict_count) values '

    # for data in data_list:
    kkbh = data['kkbh']
    day = data['day']
    hour = data['hour']
    predict_count = data['predict_count']
    sql += "('{}','{}','{}',{})".format(kkbh, day, hour, predict_count)

    ClickHouseUtil().exec(sql)


# 同步数据
def sync_data():
    # time.strftime('%Y-%m-%d', time.localtime(time.time()))
    sql = '''
            select '' as `kkbh`, toDate('2021-02-01') as `day`, '' as `hour`, 12 as `real_count`
        '''
    #     where `xxx` between subtractMinutes(now(), 24 * 60 + 30) and subtractMinutes(now(), 30)

    data_list = ClickHouseUtil().exec(sql)
    if data_list and len(data_list) > 0:
        sql = 'insert into t_car_flow_history(kkbh, day, hour, real_count) values '

        for data in data_list:
            kkbh = data[0]
            day = data[1]
            hour = data[2]
            real_count = data[3]
            sql += "('{}','{}','{}',{}),".format(kkbh, day, hour, real_count)

        sql = sql[:-1]
        ClickHouseUtil().exec(sql)


# 获取卡口编号信息
def fetch_kkbh_list():
    sql = '''
            select 
                kkbh
            from
                t_car_flow_kkbh
        '''
    bayonet_list = ClickHouseUtil().exec_pd(sql)
    bayonet_list = np.hstack(bayonet_list.values)
    return bayonet_list

if __name__ == '__main__':
    data = fetch_data('621', '2021-01-24', '2021-06-23', '01')
    print(data)